package ensemble.controls

import javafx.scene.layout.{VBox, Region}
import javafx.scene.control.{Button, TextField}
import javafx.beans.value.ObservableValue
import javafx.scene.input.KeyCode
import net.oschina.oldpig.snout._
import javafx.scene.{Node, layout}

object SearchBox extends NodeFactory[Region] {

  import FxBuilder._

  val infoBox = is[VBox]
  val textBox = is[TextField]
  val clearButton = is[Button]

  lazy val extraInfoPopup = popup() {
    vBox(id := "search-info-box", fillWidth := true, minWidth := Region.USE_PREF_SIZE, prefWidth := 350) {
      label(id := "search-info-name", minWidth := Region.USE_PREF_SIZE, prefHeight := 28)
      label(id := "search-info-description", wrapText := true, prefWidth := infoBox.getPrefWidth - 24)
    } as infoBox
  }
  val cxtMenu = contextMenu(onHidden := { _ => extraInfoPopup.hide()})

  override def createInstance = {
    val me = new Region with Customized {
      override def layoutChildren() {
        textBox.resize(getWidth, getHeight)
        clearButton.resizeRelocate(getWidth - 18, 6, 12, 13)
      }

      def adopt(node: Node) = this.getChildren.add(node)
    }

    builderParent.withValue(me) {
      textField(promptText := "Search", onKeyReleased := { ke =>
        if (ke.getCode == KeyCode.DOWN)
          cxtMenu.requestFocus()
      }, onPropertyChanged :=(textProperty, onTextChanged)) as textBox
      button(visible := false, onAction := { _ =>
        textBox.setText("")
        textBox.requestFocus()
      }) as clearButton
    }
    me
  }

  def onTextChanged(ob: ObservableValue[_ <: String], old: String, _new: String): Unit = {
    clearButton.setVisible(textBox.getText.length != 0)
  }

  def populateMenu() {

  }
}
